{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WKIIJrOaR2rL"
      },
      "source": [
        "**Copyright 2021 The TensorFlow Authors.**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "mEE8NFIMSGO-"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MfBg1C5NB3X0"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/model_optimization/guide/combine/cqat_example\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/model-optimization/blob/master/tensorflow_model_optimization/g3doc/guide/combine/cqat_example.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/model-optimization/blob/master/tensorflow_model_optimization/g3doc/guide/combine/cqat_example.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/model-optimization/tensorflow_model_optimization/g3doc/guide/combine/cqat_example.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SyiSRgdtSGPC"
      },
      "source": [
        "# Cluster preserving quantization aware training (CQAT) Keras example"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dKnJyAaASGPD"
      },
      "source": [
        "## Overview\n",
        "\n",
        "This is an end to end example showing the usage of the **cluster preserving quantization aware training (CQAT)** API, part of the TensorFlow Model Optimization Toolkit's collaborative optimization pipeline.\n",
        "\n",
        "### Other pages\n",
        "\n",
        "For an introduction to the pipeline and other available techniques, see the [collaborative optimization overview page](https://www.tensorflow.org/model_optimization/guide/combine/collaborative_optimization).\n",
        "\n",
        "### Contents\n",
        "\n",
        "In the tutorial, you will:\n",
        "\n",
        "1. Train a `tf.keras` model for the MNIST dataset from scratch.\n",
        "2. Fine-tune the model with clustering and see the accuracy.\n",
        "3. Apply QAT and observe the loss of clusters.\n",
        "4. Apply CQAT and observe that the clustering applied earlier has been preserved.\n",
        "5. Generate a TFLite model and observe the effects of applying CQAT on it.\n",
        "6. Compare the achieved CQAT model accuracy with a model quantized using post-training quantization."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RgcQznnZSGPE"
      },
      "source": [
        "## Setup\n",
        "\n",
        "You can run this Jupyter Notebook in your local [virtualenv](https://www.tensorflow.org/install/pip?lang=python3#2.-create-a-virtual-environment-recommended) or [colab](https://colab.sandbox.google.com/). For details of setting up dependencies, please refer to the [installation guide](https://www.tensorflow.org/model_optimization/guide/install). "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3asgXMqnSGPE"
      },
      "outputs": [],
      "source": [
        "! pip install -q tensorflow-model-optimization"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gL6JiLXkSGPI"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "\n",
        "import numpy as np\n",
        "import tempfile\n",
        "import zipfile\n",
        "import os"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dKzOfl5FSGPL"
      },
      "source": [
        "## Train a tf.keras model for MNIST without clustering"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "w7Fd6jZ7SGPL"
      },
      "outputs": [],
      "source": [
        "# Load MNIST dataset\n",
        "mnist = tf.keras.datasets.mnist\n",
        "(train_images, train_labels), (test_images, test_labels) = mnist.load_data()\n",
        "\n",
        "# Normalize the input image so that each pixel value is between 0 to 1.\n",
        "train_images = train_images / 255.0\n",
        "test_images  = test_images / 255.0\n",
        "\n",
        "model = tf.keras.Sequential([\n",
        "  tf.keras.layers.InputLayer(input_shape=(28, 28)),\n",
        "  tf.keras.layers.Reshape(target_shape=(28, 28, 1)),\n",
        "  tf.keras.layers.Conv2D(filters=12, kernel_size=(3, 3),\n",
        "                         activation=tf.nn.relu),\n",
        "  tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),\n",
        "  tf.keras.layers.Flatten(),\n",
        "  tf.keras.layers.Dense(10)\n",
        "])\n",
        "\n",
        "# Train the digit classification model\n",
        "model.compile(optimizer='adam',\n",
        "              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "              metrics=['accuracy'])\n",
        "\n",
        "model.fit(\n",
        "    train_images,\n",
        "    train_labels,\n",
        "    validation_split=0.1,\n",
        "    epochs=10\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rBOQ8MeESGPO"
      },
      "source": [
        "### Evaluate the baseline model and save it for later usage"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "HYulekocSGPP"
      },
      "outputs": [],
      "source": [
        "_, baseline_model_accuracy = model.evaluate(\n",
        "    test_images, test_labels, verbose=0)\n",
        "\n",
        "print('Baseline test accuracy:', baseline_model_accuracy)\n",
        "\n",
        "_, keras_file = tempfile.mkstemp('.h5')\n",
        "print('Saving model to: ', keras_file)\n",
        "tf.keras.models.save_model(model, keras_file, include_optimizer=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cWPgcnjKSGPR"
      },
      "source": [
        "## Cluster and fine-tune the model with 8 clusters"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Y2wKK7w9SGPS"
      },
      "source": [
        "Apply the `cluster_weights()` API to cluster the whole pre-trained model to demonstrate and observe its effectiveness in reducing the model size when applying zip, while maintaining accuracy. For how best to use the API to achieve the best compression rate while maintaining your target accuracy, refer to the [clustering comprehensive guide](https://www.tensorflow.org/model_optimization/guide/clustering/clustering_comprehensive_guide)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ea40z522SGPT"
      },
      "source": [
        "### Define the model and apply the clustering API"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7aOB5vjOZMTS"
      },
      "source": [
        "The model needs to be pre-trained before using the clustering API."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "OzqKKt0mSGPT"
      },
      "outputs": [],
      "source": [
        "import tensorflow_model_optimization as tfmot\n",
        "\n",
        "cluster_weights = tfmot.clustering.keras.cluster_weights\n",
        "CentroidInitialization = tfmot.clustering.keras.CentroidInitialization\n",
        "\n",
        "clustering_params = {\n",
        "  'number_of_clusters': 8,\n",
        "  'cluster_centroids_init': CentroidInitialization.KMEANS_PLUS_PLUS\n",
        "}\n",
        "\n",
        "clustered_model = cluster_weights(model, **clustering_params)\n",
        "\n",
        "# Use smaller learning rate for fine-tuning\n",
        "opt = tf.keras.optimizers.Adam(learning_rate=1e-5)\n",
        "\n",
        "clustered_model.compile(\n",
        "  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "  optimizer=opt,\n",
        "  metrics=['accuracy'])\n",
        "\n",
        "clustered_model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ev4MyClmSGPW"
      },
      "source": [
        "### Fine-tune the model and evaluate the accuracy against baseline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vQoy9CcASGPX"
      },
      "source": [
        "Fine-tune the model with clustering for 3 epochs."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "jn29-coXSGPX"
      },
      "outputs": [],
      "source": [
        "# Fine-tune model\n",
        "clustered_model.fit(\n",
        "  train_images,\n",
        "  train_labels,\n",
        "  epochs=3,\n",
        "  validation_split=0.1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "iHCYA7twR2ro"
      },
      "source": [
        "Define helper functions to calculate and print the number of clustering in each kernel of the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "f3gf1TDjR2rp"
      },
      "outputs": [],
      "source": [
        "def print_model_weight_clusters(model):\n",
        "\n",
        "    for layer in model.layers:\n",
        "        if isinstance(layer, tf.keras.layers.Wrapper):\n",
        "            weights = layer.trainable_weights\n",
        "        else:\n",
        "            weights = layer.weights\n",
        "        for weight in weights:\n",
        "            # ignore auxiliary quantization weights\n",
        "            if \"quantize_layer\" in weight.name:\n",
        "                continue\n",
        "            if \"kernel\" in weight.name:\n",
        "                unique_count = len(np.unique(weight))\n",
        "                print(\n",
        "                    f\"{layer.name}/{weight.name}: {unique_count} clusters \"\n",
        "                )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QS3VBSXAR2rq"
      },
      "source": [
        "Check that the model kernels were correctly clustered. We need to strip the clustering wrapper first."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "5l1jOLMfR2rq"
      },
      "outputs": [],
      "source": [
        "stripped_clustered_model = tfmot.clustering.keras.strip_clustering(clustered_model)\n",
        "\n",
        "print_model_weight_clusters(stripped_clustered_model)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dvaZKoxtTORx"
      },
      "source": [
        "For this example, there is minimal loss in test accuracy after clustering, compared to the baseline."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bE7MxpWLTaQ1"
      },
      "outputs": [],
      "source": [
        "_, clustered_model_accuracy = clustered_model.evaluate(\n",
        "  test_images, test_labels, verbose=0)\n",
        "\n",
        "print('Baseline test accuracy:', baseline_model_accuracy)\n",
        "print('Clustered test accuracy:', clustered_model_accuracy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VXfPMa6ISGPd"
      },
      "source": [
        "## Apply QAT and CQAT and check effect on model clusters in both cases"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1zr_QIhcUeuC"
      },
      "source": [
        "Next, we apply both QAT and cluster preserving QAT (CQAT) on the clustered model and observe that CQAT preserves weight clusters in your clustered model. Note that we stripped clustering wrappers from your model with `tfmot.clustering.keras.strip_clustering` before applying CQAT API."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4h6tSvMzSGPd"
      },
      "outputs": [],
      "source": [
        "# QAT\n",
        "qat_model = tfmot.quantization.keras.quantize_model(stripped_clustered_model)\n",
        "\n",
        "qat_model.compile(optimizer='adam',\n",
        "              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "              metrics=['accuracy'])\n",
        "print('Train qat model:')\n",
        "qat_model.fit(train_images, train_labels, batch_size=128, epochs=1, validation_split=0.1)\n",
        "\n",
        "# CQAT\n",
        "quant_aware_annotate_model = tfmot.quantization.keras.quantize_annotate_model(\n",
        "              stripped_clustered_model)\n",
        "cqat_model = tfmot.quantization.keras.quantize_apply(\n",
        "              quant_aware_annotate_model,\n",
        "              tfmot.experimental.combine.Default8BitClusterPreserveQuantizeScheme())\n",
        "\n",
        "cqat_model.compile(optimizer='adam',\n",
        "              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "              metrics=['accuracy'])\n",
        "print('Train cqat model:')\n",
        "cqat_model.fit(train_images, train_labels, batch_size=128, epochs=1, validation_split=0.1)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-25FRoM0R2rt"
      },
      "outputs": [],
      "source": [
        "print(\"QAT Model clusters:\")\n",
        "print_model_weight_clusters(qat_model)\n",
        "print(\"CQAT Model clusters:\")\n",
        "print_model_weight_clusters(cqat_model)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rdUFrE9CR2ru"
      },
      "source": [
        "## See compression benefits of CQAT model\n",
        "\n",
        "Define helper function to get zipped model file."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gc5txUkwR2ru"
      },
      "outputs": [],
      "source": [
        "def get_gzipped_model_size(file):\n",
        "  # It returns the size of the gzipped model in kilobytes.\n",
        "\n",
        "  _, zipped_file = tempfile.mkstemp('.zip')\n",
        "  with zipfile.ZipFile(zipped_file, 'w', compression=zipfile.ZIP_DEFLATED) as f:\n",
        "    f.write(file)\n",
        "\n",
        "  return os.path.getsize(zipped_file)/1000"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "405ju8jER2ru"
      },
      "source": [
        "Note that this is a small model. Applying clustering and CQAT to a bigger production model would yield a more significant compression."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "OChikLlhR2rv"
      },
      "outputs": [],
      "source": [
        "# QAT model\n",
        "converter = tf.lite.TFLiteConverter.from_keras_model(qat_model)\n",
        "converter.optimizations = [tf.lite.Optimize.DEFAULT]\n",
        "qat_tflite_model = converter.convert()\n",
        "qat_model_file = 'qat_model.tflite'\n",
        "# Save the model.\n",
        "with open(qat_model_file, 'wb') as f:\n",
        "    f.write(qat_tflite_model)\n",
        "    \n",
        "# CQAT model\n",
        "converter = tf.lite.TFLiteConverter.from_keras_model(cqat_model)\n",
        "converter.optimizations = [tf.lite.Optimize.DEFAULT]\n",
        "cqat_tflite_model = converter.convert()\n",
        "cqat_model_file = 'cqat_model.tflite'\n",
        "# Save the model.\n",
        "with open(cqat_model_file, 'wb') as f:\n",
        "    f.write(cqat_tflite_model)\n",
        "    \n",
        "print(\"QAT model size: \", get_gzipped_model_size(qat_model_file), ' KB')\n",
        "print(\"CQAT model size: \", get_gzipped_model_size(cqat_model_file), ' KB')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-zwAgK4SR2rw"
      },
      "source": [
        "## See the persistence of accuracy from TF to TFLite\n",
        "\n",
        "Define a helper function to evaluate the TFLite model on the test dataset."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BEeTH_qBR2rw"
      },
      "outputs": [],
      "source": [
        "def eval_model(interpreter):\n",
        "  input_index = interpreter.get_input_details()[0][\"index\"]\n",
        "  output_index = interpreter.get_output_details()[0][\"index\"]\n",
        "\n",
        "  # Run predictions on every image in the \"test\" dataset.\n",
        "  prediction_digits = []\n",
        "  for i, test_image in enumerate(test_images):\n",
        "    if i % 1000 == 0:\n",
        "      print(f\"Evaluated on {i} results so far.\")\n",
        "    # Pre-processing: add batch dimension and convert to float32 to match with\n",
        "    # the model's input data format.\n",
        "    test_image = np.expand_dims(test_image, axis=0).astype(np.float32)\n",
        "    interpreter.set_tensor(input_index, test_image)\n",
        "\n",
        "    # Run inference.\n",
        "    interpreter.invoke()\n",
        "\n",
        "    # Post-processing: remove batch dimension and find the digit with highest\n",
        "    # probability.\n",
        "    output = interpreter.tensor(output_index)\n",
        "    digit = np.argmax(output()[0])\n",
        "    prediction_digits.append(digit)\n",
        "\n",
        "  print('\\n')\n",
        "  # Compare prediction results with ground truth labels to calculate accuracy.\n",
        "  prediction_digits = np.array(prediction_digits)\n",
        "  accuracy = (prediction_digits == test_labels).mean()\n",
        "  return accuracy"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CiL7XluNR2rx"
      },
      "source": [
        "You evaluate the model, which has been clustered and quantized, and then see the accuracy from TensorFlow persists in the TFLite backend."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LLHIyrumR2rx"
      },
      "outputs": [],
      "source": [
        "interpreter = tf.lite.Interpreter(cqat_model_file)\n",
        "interpreter.allocate_tensors()\n",
        "\n",
        "cqat_test_accuracy = eval_model(interpreter)\n",
        "\n",
        "print('Clustered and quantized TFLite test_accuracy:', cqat_test_accuracy)\n",
        "print('Clustered TF test accuracy:', clustered_model_accuracy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YokQ0TuvR2ry"
      },
      "source": [
        "## Apply post-training quantization and compare to CQAT model\n",
        "\n",
        "Next, we use post-training quantization (no fine-tuning) on the clustered model and check its accuracy against the CQAT model. This demonstrates why you would need to use CQAT to improve the quantized model's accuracy.\n",
        "\n",
        "First, define a generator for the callibration dataset from the first 1000 training images."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LoVVjF-zR2ry"
      },
      "outputs": [],
      "source": [
        "def mnist_representative_data_gen():\n",
        "  for image in train_images[:1000]:  \n",
        "    image = np.expand_dims(image, axis=0).astype(np.float32)\n",
        "    yield [image]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KS6MMKVFR2ry"
      },
      "source": [
        "Quantize the model and compare accuracy to the previously acquired CQAT model. Note that the model quantized with fine-tuning achieves higher accuracy."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4MK8mjIuR2ry"
      },
      "outputs": [],
      "source": [
        "converter = tf.lite.TFLiteConverter.from_keras_model(stripped_clustered_model)\n",
        "converter.optimizations = [tf.lite.Optimize.DEFAULT]\n",
        "converter.representative_dataset = mnist_representative_data_gen\n",
        "post_training_tflite_model = converter.convert()\n",
        "post_training_model_file = 'post_training_model.tflite'\n",
        "# Save the model.\n",
        "with open(post_training_model_file, 'wb') as f:\n",
        "    f.write(post_training_tflite_model)\n",
        "    \n",
        "# Compare accuracy\n",
        "interpreter = tf.lite.Interpreter(post_training_model_file)\n",
        "interpreter.allocate_tensors()\n",
        "\n",
        "post_training_test_accuracy = eval_model(interpreter)\n",
        "\n",
        "print('CQAT TFLite test_accuracy:', cqat_test_accuracy)\n",
        "print('Post-training (no fine-tuning) TF test accuracy:', post_training_test_accuracy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "X1MBu6Q9R2rz"
      },
      "source": [
        "## Conclusion"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7JhbpowqSGP1"
      },
      "source": [
        "In this tutorial, you learned how to create a model, cluster it using the `cluster_weights()` API, and apply the cluster preserving quantization aware training (CQAT) to preserve clusters while using QAT. The final CQAT model was compared to the QAT one to show that the clusters are preserved in the former and lost in the latter. Next, the models were converted to TFLite to show the compression benefits of chaining clustering and CQAT model optimization techniques and the TFLite model was evaluated to ensure that the accuracy persists in the TFLite backend. Finally, the CQAT model was compared to a quantized clustered model achieved using the post-training quantization API to demonstrate the advantage of CQAT in recovering the accuracy loss from normal quantization."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "cqat_example.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
